﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Collections;
using System.Web.UI.WebControls;

namespace Trig_AMJ_HR_Forms.Layouts.Trig_AMJ_HR_Forms
{

    #region "Old Ref"

    #endregion

    public partial class Resumption_Duty_Form : LayoutsPageBase
    {
        SPHelper obj = new SPHelper();
        Demand_Voucher_FormClass demandVoucherclass = new Demand_Voucher_FormClass(); // Helper class for this solution
        Trig_WF trigWFClass = new Trig_WF();


        #region "Properties"

        string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;

        public static string SiteURL;
        public static string ResumpRequestNo;
        public static string SourceLstName;
        public static string MainLstName;
        public static string TaskLstName;
        public static string AttLibName;
        public static string CmntsLstName;
        public static string WorkflowConfigList;
        public static string lstGuid { get; set; }
        public string camlQry { get; set; }
        public static string Mode { get; set; }
        public static string submittedfor { get; set; }
        string ErrorMsgs;
        public static int wfOrder = 0;
        public static string DocumentTypesList { get; set; }
        string WFCurrentOrder = string.Empty;
        string WFTaskType = string.Empty;

        public static string LeaveRefID;
        public static string refID;
        private static bool Submit = false;

        public static int ResumpItemID;


        object[] ResumptionParams;

        private static SPListItemCollection oItemsColl = null;
        public static SPListItem oItems = null;

        public static string RequestType = null;

        string[] buttonVisibilty = new string[5];


        #endregion


        public Resumption_Duty_Form()
        {
            SiteURL = SPContext.Current.Site.Url;
            SiteURL = SiteURL + "/sites/forms/";
            MainLstName = "Resumption of Duty Forms";
            TaskLstName = "Resumption of Duty Tasks";
            CmntsLstName = "Resumption of Duty Comments";
            SourceLstName = "Leave Request Forms";
            AttLibName = "Attachments";
            WorkflowConfigList = "Workflow Configuration List";
            DocumentTypesList = "DocumentTypes";

        }


        protected void Page_Load(object sender, EventArgs e)
        {
            lblError.Text = "";
            lblErrors.Text = "";
            try
            {
                if (!IsPostBack)
                {
                    dtHandoverDt.SelectedDate = DateTime.Today;
                    Submit = false;
                    Mode = Request.QueryString["Mode"];
                    refID = Request.QueryString["RefID"]; // From Dashboard.
                    LeaveRefID = Request.QueryString["LeaveRefID"]; // From Leave Request Dashboard.

                    dtpDate.SelectedDate = DateTime.Today;

                    ImgUser.ImageUrl = demandVoucherclass.GetUserProfilePictureURL(CurrentUser);
                    LblCommentsUserName.Text = CurrentUser;


                    if (Mode == "Edit" || Mode == "View")
                    {
                        SPSecurity.RunWithElevatedPrivileges(delegate()
                        {
                            FormApprovalLoad();
                            GetUserInfo();
                            if (Mode == "View") InvisibleButtons();
                            pplReqUser.Enabled = false;
                        });
                    }
                    else if (Mode == "New")
                    {
                        dtpDate.SelectedDate = DateTime.Today.Date;
                        if (refID != null || LeaveRefID != null)
                            FirstLoadofForm();
                    }
                    else
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Unable to open the form. Value is missing. Contact administrator";
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "Page_Load";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

            // Set submit status is useful to avoid the below functionality process while the form gets Submit
            if (Mode == "New" && ckSubmit.Value == "false") GetUserInfo();

        }

        private void GetUserInfo()
        {
            ClearResumptionControls();

            if (LeaveRefID != null) // This id gets from Leave Request Dashboard or gets from ReLoadDetails method, it will get leave user and assign user to PeopleEditor conmtrols
            {
                GetLeaveUser(pplReqUser);
            }

            else if (pplReqUser.ResolvedEntities.Count > 0)
            {
                PickerEntity pe = (PickerEntity)pplReqUser.Entities[0];
                string submittedFor = pe.DisplayText;

                camlQry = "<Where><And><Eq><FieldRef Name=\"SubmittedFor\" /><Value Type=\"User\">" + submittedFor + "</Value></Eq><Eq>" +
                    "<FieldRef Name=\"ResumptionStatus\" /><Value Type=\"Text\">No</Value></Eq></And></Where>";
                oItems = obj.GetSPListItem(SiteURL, SourceLstName, camlQry);
                if (oItems != null)
                {
                    //To check whether the corresponding leave reference is in Resumption of Duty form list or not

                    if (!CheckEntryForm(Convert.ToString(oItems["Reference_x0020_Number"]))) { SetControlsValue(oItems); btnSubmit.Visible = true; }
                    else
                    {
                        btnSubmit.Visible = false; lblErrors.Visible = true; lblErrors.Text = "Resumption status for the corresponding Leave is In Progress";
                    }
                }
                else
                {
                    btnSubmit.Visible = false; lblErrors.Visible = true; lblErrors.Text = "No Leave records for selected user";
                }
            }
        }


        /// <summary>
        /// Set status depends upon leave reference is in Resumption of Duty form list
        /// </summary>
        /// <param name="LeaverefID"></param>
        /// <returns></returns>
        private bool CheckEntryForm(string LeaverefID)
        {
            bool ckResStatus = false;
            try
            {
                SPQuery qry = new SPQuery();
                camlQry = "<Where><Eq><FieldRef Name=\"LeaveReferenceNo\" /><Value Type=\"Text\">" + LeaverefID + "</Value></Eq></Where>";
                qry.Query = camlQry;
                qry.ViewFields = "<FieldRef Name='LeaveReferenceNo' />";
                SPListItem oItem = obj.GetSPListItem(SiteURL, MainLstName, qry);
                if (oItem != null)
                    ckResStatus = true;
                else
                    ckResStatus = false;

            }
            catch (Exception ex)
            {
                // GenerateExceptionLog("Leave_Request_DashboardUserControl : ", ex.Message, "CheckResumption");
            }
            return ckResStatus;
        }


        /// <summary>
        /// Get user leave records from Leave Request Form
        /// </summary>
        /// <param name="ppls"></param>
        private void GetLeaveUser(PeopleEditor ppls)
        {
            ArrayList _arrayList = new ArrayList();

            SPFieldUserValue fldUser = null;
            SPQuery qry = new SPQuery();
            camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + LeaveRefID + "</Value></Eq></Where>";
            qry.Query = camlQry;
            //qry.ViewFields = "<FieldRef Name='SubmittedFor' />";
            oItems = obj.GetSPListItem(SiteURL, SourceLstName, qry);
            if (oItems != null)
            {
                fldUser = new SPFieldUserValue(SPContext.Current.Web, Convert.ToString(oItems["SubmittedFor"]));

                PickerEntity _pickerEntity = new PickerEntity(); // PickerEntitiy use using Microsoft.SharePoint.WebControls
                _pickerEntity.Key = fldUser.LookupValue;
                _pickerEntity.IsResolved = true;
                _arrayList.Add(_pickerEntity);
                ppls.UpdateEntities(_arrayList);
                SetControlsValue(oItems);

                submittedfor = fldUser.LookupValue;
            }
            else
            {

            }
        }


        /// <summary>
        /// Set values on the controls while Form gets ReLoaded
        /// </summary>
        /// <param name="oItems"></param>
        private void SetControlsValue(SPListItem oItems)
        {
            txtReqEmpId.Text = Convert.ToString(oItems["EmployeeID"]);
            txtReqDivision.Text = Convert.ToString(oItems["Division"]);
            txtReqDesignation.Text = Convert.ToString(oItems["Designation"]);
            txtReqDepartment.Text = Convert.ToString(oItems["Department"]);
            txtPastportNo.Text = Convert.ToString(oItems["PassportNo"]);

            if (string.IsNullOrEmpty(Convert.ToString(oItems["LeaveOthers"])))
                txtLeaveType.Text = Convert.ToString(oItems["LeaveType"]);
            else
                txtLeaveType.Text = Convert.ToString(oItems["LeaveType"]) + " - " + Convert.ToString(oItems["LeaveOthers"]);

            txtLeaveType.Text = Convert.ToString(oItems["LeaveType"]);
            dtTravelDt.SelectedDate = Convert.ToDateTime(oItems["TravelDate"]);
            dtReturnDt.SelectedDate = Convert.ToDateTime(oItems["ReturnDate"]);
            lblLevReqNo.Text = Convert.ToString(oItems["Reference_x0020_Number"]);
            dtLeaveReqDate.SelectedDate = Convert.ToDateTime(oItems["RequestDate"]);
        }

        private void ClearResumptionControls()
        {
            txtReqEmpId.Text = "";
            txtReqDivision.Text = "";
            txtReqDesignation.Text = "";
            txtPastportNo.Text = "";
            txtLeaveType.Text = "";
            dtTravelDt.ClearSelection();
            dtReturnDt.ClearSelection();
            lblLevReqNo.Text = "";
            dtLeaveReqDate.ClearSelection();

            if (Mode == "New")
            {
                txtExcessLeaveDays.Text = "";
                txtAction.Text = "";
                dtReturnDt.ClearSelection();
            }

        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {

            if (Request.QueryString["Mode"] == "Edit")
            {
                string formID = null;
                string refNo = Request.QueryString["RefID"];
                string taskItemID = Request.QueryString["TaskItemID"];
                string Approver = SPContext.Current.Web.CurrentUser.LoginName;

                if (GetSendbackStatus())
                {
                    if (CheckServersideValidation())
                    {
                        SPLongOperation lop = new SPLongOperation(this.Page);
                        lop.LeadingHTML = "<DIV><H4>Resumption of Duty form approval is in progress</H4></DIV>";
                        lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                        lop.Begin();
                        obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID,
                            WFTaskType, Approver, TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, false, 2, null);
                        UpdatePRO_Status();
                        lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");

                    }
                }
                else
                {
                    lblError.Text = "Can't be send back. User is not available";
                }
            }
            else if (Request.QueryString["Mode"] == "New")
            {
                Submit = true;
                SaveFormDetails();
                ClientScript.RegisterClientScriptBlock(GetType(), "Record Saved", "window.close", true);
            }

        }

        /// <summary>
        /// Save Form details to Main List
        /// Add Items in Main List
        /// Add Items in Task List
        /// Add Items in Comments List
        /// Add Attachment to Attachment Library
        /// </summary>

        private void SaveFormDetails()
        {
            SPLongOperation lop = new SPLongOperation(this.Page);
            lop.LeadingHTML = "<DIV><H4>Resumption of Duty form submission is in progress...</H4></DIV>";
            lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
            lop.Begin();

            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    obj.AutoNoGeneration(MainLstName, DocumentTypesList, lblResumpReqNo, SiteURL);
                    ResumpRequestNo = Convert.ToString(lblResumpReqNo.Text).Trim();
                    if (ResumpRequestNo.Contains(DateTime.Now.Year.ToString()))
                    {

                        cntrls(lblLevReqNo.Text, dtLeaveReqDate.SelectedDate.Date, pplReqUser.CommaSeparatedAccounts, txtReqEmpId.Text, txtReqDivision.Text, txtReqDesignation.Text, txtPastportNo.Text,
                           txtLeaveType.Text, dtTravelDt.SelectedDate.Date, dtReturnDt.SelectedDate.Date, dtResumptionDt.SelectedDate.Date, txtExcessLeaveDays.Text, txtAction.Text, txtReqDepartment.Text);

                        lstGuid = obj.AddResumption_Items(SiteURL, MainLstName, TaskLstName, CmntsLstName, AttLibName, upfile, WorkflowConfigList, pplcnt,
                            lblResumpReqNo.Text, dtpDate.SelectedDate.Date, CurrentUser,
                            ResumptionParams, TxtComments.Text);
                    }
                    else
                    {
                        lblError.Text = "Master list details not in Doecument Types"; lblError.ForeColor = System.Drawing.Color.Red;
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "SaveFormDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
            lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");

        }

        private void cntrls(params object[] parameter)
        {
            ResumptionParams = parameter;
        }

        /// <summary>
        /// Set Handedover and HandoverDate valus while the forms gets submitted by pro user
        /// </summary>
        private void UpdatePRO_Status()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            oWeb.AllowUnsafeUpdates = true;
                            oItems = oWeb.Lists.TryGetList(MainLstName).GetItemById(ResumpItemID);
                            if (oItems != null)
                            {
                                oItems["Handedover"] = Convert.ToInt32(confirm.Checked);
                                if (confirm.Checked)
                                    oItems["HandoverDate"] = Convert.ToDateTime(dtHandoverDt.SelectedDate);
                                oItems.Update();
                            }
                            oWeb.AllowUnsafeUpdates = false;
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "UpdatePRO_Status";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        /// <summary>
        /// To check whether the Form is in Document Types master list or not.
        /// Also get the document prefix and starting number of the form
        /// Otherwise the user gets Access Denied
        /// </summary>
        private void FirstLoadofForm()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string[] getDocRefNumber = demandVoucherclass.getRefNum(SiteURL, DocumentTypesList, MainLstName);
                    if (string.IsNullOrEmpty(getDocRefNumber[0]) && string.IsNullOrEmpty(getDocRefNumber[1]))
                    {
                        pnlFullForm.Visible = false;
                        pnlAccessDenied.Visible = true;
                        lblAccessDeniedMsg.Visible = true;
                        lblAccessDeniedMsg.Text = "Access Denied, DocPrefix or Starting Number column value in Document Types Master list is missing. Contact administrator.";
                    }

                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "FirstLoadofForm";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        /// <summary>
        /// check the user availability
        /// </summary>
        /// <returns></returns>

        public bool GetSendbackStatus()
        {
            bool status = true;
            if (rtbSendBack.Checked)
            {
                SPFieldUserValue ofldUser = demandVoucherclass.getSendBackUserfNametoAssignLabelText(SiteURL, TaskLstName, Convert.ToInt16(Request.Params["TaskItemID"]), lblResumpReqNo.Text, rtbSendBack, rtbForward, lblError);
                if (ofldUser == null)
                {
                    status = false;
                }
            }
            return status;
        }

        /// <summary>
        /// Check people editor validations
        /// </summary>
        /// <returns></returns>

        public bool CheckServersideValidation()
        {
            bool rval = true;
            if (rtbForwardOthers.Checked)
            {
                if (pplcnt.Accounts.Count > 0)
                {
                    rval = true;
                }
                else
                {
                    rval = false;
                    lblError.Text = "Please enter the user name to forward";
                }
            }
            return rval;
        }

        /// <summary>
        /// Radio button visibility for dynamic users
        /// </summary>
        /// <param name="tasktype"></param>
        /// <param name="optional"></param>
        /// <param name="OptionalUserName"></param>

        public void RadioButtionListvisibility(SPWeb oweb, string tasktype, bool optional, string OptionalUserName, int WFOrder)
        {
            try
            {
                if (Request.QueryString["Mode"] == "New")
                {
                    pnlForward.Visible = false;
                }
                else if (Request.QueryString["Mode"] == "Edit")
                {
                    if (tasktype == "Static")
                    {
                        pnlForward.Visible = false;
                    }
                    else if (tasktype == "Dynamic")
                    {
                        setRadioButtonVisibilityforDynamicType(WFOrder);
                    }
                    else if (tasktype == "UP Attribute")
                    {
                        pnlForward.Visible = false;
                    }
                    else if (tasktype == "EC (Externally Configured)")
                    {
                        pnlForward.Visible = false;
                    }

                    buttonVisibilty = demandVoucherclass.getForwardbuttonVisibility(SiteURL, WorkflowConfigList, MainLstName, WFOrder);
                    if (buttonVisibilty[3] == "True")
                    {
                        btnApprove.Visible = true;
                        btnReject.Visible = true;
                        btnSubmit.Visible = false;
                    }
                    else
                    {
                        btnApprove.Visible = false;
                        btnReject.Visible = false;
                        btnSubmit.Visible = true;
                    }
                    if (buttonVisibilty[4] == "False")
                    {
                        pnlCommentArea.Visible = false;
                    }

                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "RadioButtionListvisibility";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }

        /// <summary>
        /// set radion buttons visibilty for the dynamic work flow users
        /// </summary>
        /// <param name="WFOrder"></param>

        public void setRadioButtonVisibilityforDynamicType(int WFOrder)
        {
            try
            {
                buttonVisibilty = demandVoucherclass.getForwardbuttonVisibility(SiteURL, WorkflowConfigList, MainLstName, WFOrder);
                if (buttonVisibilty[0] == "True")
                {
                    rtbSendBack.Visible = true;
                    rtbSendBack.Checked = true;
                }
                else
                {
                    rtbSendBack.Visible = false;
                }
                if (buttonVisibilty[1] == "True")
                {
                    rtbForwardOthers.Visible = true;
                }
                else
                {
                    rtbForwardOthers.Visible = false;
                }

                if (buttonVisibilty[2] == "True")
                {
                    rtbForward.Visible = true;
                }
                else
                {
                    rtbForward.Visible = false;
                }
                if (buttonVisibilty[0] == "False" && buttonVisibilty[1] == "False" && buttonVisibilty[2] == "False")
                {
                    pnlForward.Visible = false;
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms" + " :: " + "Parent" + " :: " + "setRadioButtonVisibilityforDynamicType";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        /// <summary>
        /// Get Approver user from task list and check their properties from Workflow Configuration List
        /// Based upon the properties the buttons and radio button should be shown in the screen.
        /// Also bind Submitted details from Master List
        /// </summary>
        public void FormApprovalLoad()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    string TaskItemID = Convert.ToString(Request.QueryString["TaskItemID"]);
                    if (!string.IsNullOrEmpty(TaskItemID))
                    {
                        using (SPSite FrmSite = new SPSite(SiteURL))
                        {
                            using (SPWeb frmweb = FrmSite.OpenWeb())
                            {
                                SPQuery updatecamQ = new SPQuery();
                                updatecamQ.Query = "<Where><Eq><FieldRef Name='ID' /><Value Type='Counter'>" + TaskItemID + "</Value></Eq></Where>";
                                if (frmweb.Lists.TryGetList(TaskLstName) != null)
                                {
                                    SPListItemCollection oitemcoll = frmweb.Lists.TryGetList(TaskLstName).GetItems(updatecamQ);
                                    if (oitemcoll.Count > 0)
                                    {
                                        SPListItem oitm = oitemcoll[0];
                                        WFCurrentOrder = Convert.ToString(oitm["WFCurrentOrder"]);
                                        WFTaskType = Convert.ToString(oitm["WFTaskType"]);
                                        if (WFTaskType == "Dynamic")
                                        {
                                            pnlForward.Visible = true;
                                        }
                                        RadioButtionListvisibility(frmweb, WFTaskType, false, "", Convert.ToInt32(WFCurrentOrder));
                                    }
                                }
                            }
                        }
                    }
                    ReLoadDetails();
                    //ControlsReadOnly();
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "FormApprovalLoad";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }


        #region "Reload Forms"

        public void ReLoadDetails()
        {
            try
            {
                txtExcessLeaveDays.ReadOnly = true;
                txtAction.ReadOnly = true;
                dtResumptionDt.Enabled = false;

                if (refID != null)
                    camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + refID + "</Value></Eq></Where>";
                if (LeaveRefID != null)
                    camlQry = "<Where><Eq><FieldRef Name=\"LeaveReferenceNo\" /><Value Type=\"Text\">" + LeaveRefID + "</Value></Eq></Where>";

                SPListItem lstDatas = obj.GetSPListItem(SiteURL, MainLstName, camlQry);
                if (lstDatas != null)
                {
                    lblResumpReqNo.Text = Convert.ToString(lstDatas["Reference Number"]);
                    dtpDate.SelectedDate = Convert.ToDateTime(lstDatas["RequestDate"]);
                    LeaveRefID = Convert.ToString(lstDatas["LeaveReferenceNo"]);

                    if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["ExcessLeaveDays"])))
                    {
                        txtExcessLeaveDays.Visible = false;
                        txtExcessLeaveDays.Text = Convert.ToString(lstDatas["ExcessLeaveDays"]);
                        txtExcLeaveDays.Text = Convert.ToString(lstDatas["ExcessLeaveDays"]); txtExcLeaveDays.Visible = true;
                        remember.Checked = true;
                        remember.Disabled = true;
                    }

                    txtAction.Text = Convert.ToString(lstDatas["Action"]);
                    dtResumptionDt.SelectedDate = Convert.ToDateTime(lstDatas["ResumptionDate"]);
                    dtLeaveReqDate.SelectedDate = Convert.ToDateTime(lstDatas["LeaveRequestDate"]);

                    ResumpItemID = Convert.ToInt32(lstDatas["ID"]);

                    if (!string.IsNullOrEmpty(Convert.ToString(lstDatas["Handedover"])))
                    {
                        confirm.Checked = true;
                        confirm.Disabled = true;
                        dtHandoverDt.SelectedDate = Convert.ToDateTime(lstDatas["HandoverDate"]);
                        dtHandoverDt.Enabled = false;
                    }

                    lstGuid = lstDatas.ParentList.ID.ToString();

                    Label lblreferenceNumber = ResumpCmnts.FindControl("lblReferenceNumber") as Label;
                    Label lblSiteUrl = ResumpCmnts.FindControl("lblSiteUrl") as Label;
                    Label lblfrmListName = ResumpCmnts.FindControl("lblfrmListName") as Label;
                    Label lbldocumentypesList = ResumpCmnts.FindControl("lbldocumentTypes") as Label;
                    Label lblCommentsList = ResumpCmnts.FindControl("lblCommentsList") as Label;
                    Label lblTaskList = ResumpCmnts.FindControl("lblTaskList") as Label;

                    lblTaskList.Text = TaskLstName;
                    lblCommentsList.Text = CmntsLstName;
                    lblfrmListName.Text = MainLstName;
                    lbldocumentypesList.Text = DocumentTypesList;
                    lblreferenceNumber.Text = lblResumpReqNo.Text;
                    lblSiteUrl.Text = SiteURL;
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "ReLoadDetails";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }
        }

        #endregion

        private void InvisibleButtons()
        {
            btnCntrls.Visible = false;
            pnlView.Visible = true;
            btnSubmit.Visible = false;
            btnApprove.Visible = false;
            btnReject.Visible = false;
            pnlForward.Visible = false;
            pnlCommentArea.Visible = false;
            upAtt.Visible = false;
            btnCancel.Value = "Close";

        }

        void rtbForward_CheckedChanged(object sender, EventArgs e)
        {
            lblError.Text = "";
            lblWFStaticUser.Text = "If you press Submit/Approve the workflow will go to next step";
        }

        void rtbForwardOthers_CheckedChanged(object sender, EventArgs e)
        {
            lblWFStaticUser.Text = "";
            lblError.Text = "";
        }

        void rtbSendBack_CheckedChanged(object sender, EventArgs e)
        {
            lblError.Text = "";
            SPFieldUserValue ofldUser = demandVoucherclass.getSendBackUserfNametoAssignLabelText(SiteURL, TaskLstName, Convert.ToInt16(Request.Params["TaskItemID"]), lblResumpReqNo.Text, rtbSendBack, rtbForward, lblError);
            if (ofldUser != null)
            {
                lblWFStaticUser.Text = "Send back to " + ofldUser.User.Name;
                lblSendBacktoUser.Text = ofldUser.User.Name;
            }
        }

        protected void btnApprove_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                string formID = null;
                string refNo = Request.QueryString["RefID"];
                string taskItemID = Request.QueryString["TaskItemID"];
                string Approver = SPContext.Current.Web.CurrentUser.LoginName;
                if (GetSendbackStatus())
                {
                    if (CheckServersideValidation())
                    {
                        SPLongOperation lop = new SPLongOperation(this.Page);
                        lop.LeadingHTML = "<DIV><H4>Resumption of Duty form approval is in progress</H4></DIV>";
                        lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                        lop.Begin();
                        if (obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                            TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, false, 2, submittedfor))
                            ResumptionStatusInLeaveForm();
                        lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                    }
                }
                else
                {

                    //lblError.Text = "Can't be send back. User is not available";
                    SPLongOperation lop = new SPLongOperation(this.Page);
                    lop.LeadingHTML = "<DIV><H4>Resumption of Duty form approval is in progress</H4></DIV>";
                    lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                    lop.Begin();
                    if (obj.ApprovetheForm(SiteURL, MainLstName, TaskLstName, WorkflowConfigList, CmntsLstName, AttLibName, formID, refNo, taskItemID, WFTaskType, Approver,
                        TxtComments.Text, upfile, rtbForwardOthers, rtbSendBack, pplcnt, true, 2, submittedfor))
                        ResumptionStatusInLeaveForm();
                    lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");
                }
            }
        }

        protected void btnReject_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SPLongOperation lop = new SPLongOperation(this.Page);
                lop.LeadingHTML = "<DIV><H4>Resumption of Duty form rejection in progress</H4></DIV>";
                lop.TrailingHTML = "<DIV><H5>Please wait...</H5></DIV>";
                lop.Begin();

                //string formID = null;// Request.QueryString["FormID"];
                string refNo = Request.QueryString["RefID"];
                string TaskItemID = Request.QueryString["TaskItemID"];

                try
                {
                    SPFieldUserValue userValue = obj.GetSubmittedUser(SiteURL, lstGuid, refNo);
                    trigWFClass.RejectTask(SiteURL, Request.QueryString["TaskItemID"], TaskLstName, MainLstName, Request.QueryString["RefID"]);

                    if (!string.IsNullOrEmpty(upfile.FileName))
                        demandVoucherclass.AddAttachement(SiteURL, AttLibName, refNo, lstGuid, upfile);
                    // Reject user and comments updation
                    string CurrentUser = SPContext.Current.Web.CurrentUser.LoginName;
                    obj.SetCommnets(SiteURL, CmntsLstName, MainLstName, refNo, lstGuid, CurrentUser, TxtComments.Text, 0);

                }
                catch (Exception ex)
                {
                    ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty form" + " :: " + "Parent" + " :: " + "Reject";
                    obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
                }

                lop.End(SPContext.Current.Site.Url, Microsoft.SharePoint.Utilities.SPRedirectFlags.Default, this.Context, "");

            }
        }


        /// <summary>
        /// After the form gets Apprroved set the Resumption Status as Yes
        /// </summary>
        private void ResumptionStatusInLeaveForm()
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite oSite = new SPSite(SiteURL))
                    {
                        using (SPWeb oWeb = oSite.OpenWeb())
                        {
                            SPQuery qry = new SPQuery();
                            camlQry = "<Where><Eq><FieldRef Name=\"Reference_x0020_Number\" /><Value Type=\"Text\">" + LeaveRefID + "</Value></Eq></Where>";
                            qry.Query = camlQry;

                            SPList oList = oWeb.Lists.TryGetList(SourceLstName);
                            if (oList != null)
                            {
                                oWeb.AllowUnsafeUpdates = true;
                                oItems = oList.GetItems(qry)[0];
                                if (oItems != null)
                                    oItems["ResumptionStatus"] = "Yes";
                                oItems.Update();
                                UpdateLeaveMaster(oWeb);
                                oWeb.AllowUnsafeUpdates = false;
                            }
                        }
                    }
                });
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty" + " :: " + "Parent" + " :: " + "ResumptionStatusInLeaveForm";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }

        }


        /// <summary>
        /// After the form gets Approved set and update Leave Details to Leave Master List
        /// We need to add user in the Leave Master List details, before we request this form, then only it will check and updates the details. 
        /// </summary>
        /// <param name="oWeb"></param>
        private void UpdateLeaveMaster(SPWeb oWeb)
        {
            try
            {
                camlQry = "<Where><Eq><FieldRef Name=\"User\" /><Value Type=\"User\">" + submittedfor + "</Value></Eq></Where>";
                oItems = obj.GetSPListItem(SiteURL, "User Leave Master", camlQry);

                if (oItems != null)
                {
                    int ItemID = Convert.ToInt32(oItems["ID"]);
                    {
                        SPListItem ot = oWeb.Lists.TryGetList("User Leave Master").GetItemById(ItemID); ;
                        int leaveDays = (int)(dtResumptionDt.SelectedDate.Date - dtTravelDt.SelectedDate.Date).TotalDays;
                        leaveDays++;
                        int leaveTaken = Convert.ToInt32(oItems["LeaveTaken"]) + leaveDays;
                        int eligibleLeave = Convert.ToInt32(oItems["EligibleLeaveDays"]);
                        int balanceLeave = Convert.ToInt32(oItems["BalanceLeave"]);
                        int excessLeave = Convert.ToInt32(oItems["ExcessLeave"]);
                        ot["LeaveTaken"] = leaveTaken;
                        int balance = eligibleLeave - leaveTaken;
                        balanceLeave = balance > 0 ? balance : 0;
                        ot["BalanceLeave"] = balanceLeave;
                        ot["ExcessLeave"] = leaveTaken - eligibleLeave > 0 ? leaveTaken - eligibleLeave : 0;
                        ot.Update();
                    }
                }
            }
            catch (Exception ex)
            {
                ErrorMsgs = "Trig_AMJ_HR_Forms :: Resumption of Duty form" + " :: " + "Parent" + " :: " + "UpdateLeaveMaster";
                obj.GenerateExceptionLog(ErrorMsgs, ex.Message, "");
            }


        }

    }
}
